//
//  RegFirstViewController.m
//  fitnessmanage
//
//  Created by 众拳科技 on 2017/10/17.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//  注册账号页面

#import "RegFirstViewController.h"
#import "RegFirstView.h"
#import "SetPassViewController.h"
#import "VerCodeViewController.h"

@interface RegFirstViewController (){
    
    NSTimer *_timer;
    
    int _count;
}

@property(nonatomic,weak)RegFirstView *regView;

@end

@implementation RegFirstViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
 
    self.view.backgroundColor = CSWhiteColor;
 
    _count = 30;
    
    RegFirstView *regView = [[RegFirstView alloc] initWithFrame:self.view.frame];
    
    //点击获取验证码
    [regView.sendVercodeBtn addTarget:self action:@selector(checkMobileIsReg:)forControlEvents:UIControlEventTouchUpInside];
    
    [regView.nextBtn addTarget:self action:@selector(nextBtnClick)forControlEvents:UIControlEventTouchUpInside];
    
    //密码明文暗文切换
    [regView.lookBtn addTarget:self action:@selector(passwordChange:)forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:regView];
    
    self.regView = regView;
}


#pragma mark 下一步按钮点击
-(void)nextBtnClick{
    
    if (self.regView.accountRegBtn.selected) {
        
        [self accountReg];
    }
    else{
        
        [self mobileReg];
    }
}

#pragma mark 密码切换
-(void)passwordChange:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
    self.regView.passWordTF.secureTextEntry = !self.regView.passWordTF.secureTextEntry;
    
    NSString* text = self.regView.passWordTF.text;
    
    self.regView.passWordTF.text = @" ";
    
    self.regView.passWordTF.text = text;
}


#pragma mark 检查手机号是否注册
-(void)checkMobileIsReg:(UIButton *)sender{
    
    //先验证是不是手机号码
    NSString *mobile = self.regView.phoneTF.text;
    
    if (![mobile isMobileNumber]) {
        
        [MBProgressHUD showText:@"请输入正确的手机号码" toview:self.view];
        
        return;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:mobile forKey:@"phone"];
    
    [HTTPTool GET:Get_CheckPhoneReg parameters:params success:^(id responseObject) {

        if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){

            if ([[responseObject objectForKey:@"Exists"] integerValue] == 0) {

                [self sendVerCodeBtnClick:sender];
            }
            else{

                [MBProgressHUD showText:@"该手机号已经注册"];
            }
        }
        else{

            [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
        }

    } failure:^(NSError *error) {

        [MBProgressHUD showText:@"验证失败"];
    }];
}


#pragma mark 获取验证码
-(void)sendVerCodeBtnClick:(UIButton *)sender{
    
    //先验证是不是手机号码
    NSString *mobile = self.regView.phoneTF.text;
    
    if (![mobile isMobileNumber]) {
        
        [MBProgressHUD showText:@"请输入正确的手机号码" toview:self.view];
        
        return;
    }
    
    [self startTimerWithButton:sender];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];

    [params setObject:mobile forKey:@"PhoneNumber"];

    [HTTPTool POSTRaw:Post_Home_SendSMS parameters:params success:^(id responseObject) {

        if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0){

            [MBProgressHUD showText:@"发送验证码成功"];
        }
        else{

            [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
        }

    } failure:^(NSError *error) {

    }];
    
}

//启动定时器
- (void)startTimerWithButton:(UIButton *)button
{
    button.enabled = NO;
    
    if (!_timer) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            _timer = [[NSTimer alloc]initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(count:) userInfo:button repeats:YES];
            
            [[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
        });
    }
}

//倒计时
- (void)count:(NSTimer *)timer
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIButton *button = timer.userInfo;
        
        button = self.regView.sendVercodeBtn;
        
        if (_count == 0) {
            button.enabled = YES;
            [_timer invalidate];
            _timer = nil;
            _count = 30;
        }
        _count --;
        
        [button setTitle:[NSString stringWithFormat:@"%d S",_count] forState:UIControlStateDisabled];
    });
}

#pragma mark 手机注册
-(void)mobileReg{
    
    //先验证是不是手机号码
    NSString *mobile = self.regView.phoneTF.text;
    
    if (![mobile isMobileNumber]) {
        
        [MBProgressHUD showText:@"请输入正确的手机号码" toview:self.view];
        
        return;
    }
    
    NSString *verCode = self.regView.vercodeTF.text;
    
    if (!verCode || verCode.length == 0) {
        
        [MBProgressHUD showText:@"请输入验证码" toview:self.view];
        
        return;
    }
    
    [self checkVerCode:verCode andPhone:mobile];
}


/**
 检查验证码
 */
-(void)checkVerCode:(NSString *)verCode andPhone:(NSString *)phone{
    
    //Post_Home_CheckCode
    //请求token、key
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:verCode forKey:@"Code"];
    
    [params setObject:phone forKey:@"PhoneNumber"];
    
    

    [HTTPTool POSTRaw:Post_Home_CheckCode parameters:params success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);

        if (responseObject && [[responseObject objectForKey:@"code"] intValue] == 0){

            UserAccount *userAccount = [UserAccount account];

            userAccount.CellPhone = phone;

            userAccount.Name = phone;

            [UserAccount saveAccount:userAccount];
            
            //跳转设置登录密码页面
            SetPassViewController *setPassVC = [[SetPassViewController alloc] init];
            
            [self.navigationController pushViewController:setPassVC animated:YES];


            }
        else{

            [MBProgressHUD showText:@"请输入正确的验证码"];
        }

    } failure:^(NSError *error) {

    }];
    
}



#pragma mark 账号注册
-(void)accountReg{
    
    //先验证账号是不是字母加数字组合
    NSString *account = self.regView.accountTF.text;
    
    NSString *passWord = self.regView.passWordTF.text;
    
    
    if (![self isValidAccount:account]) {
        
        [MBProgressHUD showText:@"账号是字母,数字组合,长度6~18" toview:self.view];
        
        return;
    }
    
    if (!passWord || passWord.length == 0) {
        
        [MBProgressHUD showText:@"密码不能为空" toview:self.view];
        
        return;
    }
    
    UserAccount *userAccount = [UserAccount account];

    userAccount.Name = account;

    userAccount.userPassword = passWord;

    [UserAccount saveAccount:userAccount];
//
//    //跳转绑定手机页面
    VerCodeViewController *verCodeVC = [[VerCodeViewController alloc] init];

    verCodeVC.from = @"绑定手机";
    
    [self.navigationController pushViewController:verCodeVC animated:YES];
}


- (BOOL)isValidAccount:(NSString *)account {
    
    //以字母开头，只能包含“字母”，“数字”，长度6~18
    NSString *regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{4,16}$";
    
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    
    return [pre evaluateWithObject:account];
}

-(void)dealloc{
    
    [_timer invalidate];
    
    _timer = nil;
}
@end
